package com.myworld.highConcurrency;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 测试高并发线程访问工具
 */
public class CuntDownLatchUtil {
    private final Logger log = LoggerFactory.getLogger(CuntDownLatchUtil.class);
    private CountDownLatch start;
    private CountDownLatch end;
    private int pollSize=10;

    public CuntDownLatchUtil(){
        this(10);
    }
    public CuntDownLatchUtil(int pollSize){
        this.pollSize=pollSize;
        start=new CountDownLatch(1);
        end=new CountDownLatch(pollSize);
    }

    public void latch(MyFunctionalInterface functionalInterface )throws InterruptedException{
        ExecutorService executorService= Executors.newFixedThreadPool(pollSize);
        for (int i=0;i<pollSize;i++){
            Runnable run=new Runnable() {
                @Override
                public void run() {
                    try{
                        start.await();
                        functionalInterface.run();
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }finally {
                        end.countDown();
                    }
                }
            };
            executorService.submit(run);
        };
        start.countDown();  //用于控制所有的线程创建完后才开始运行线程池里的线程
        end.await();
        log.info("所有的线程执行完成..........");
        executorService.shutdown();
    }

    /**
     * JDK1.8 定义函数式接口
     */
    @FunctionalInterface
    public interface MyFunctionalInterface{
        void run();
    }
}
